package com.ctrip.corp.obt.shard.sql.parser.forbidden;

import static com.ctrip.corp.obt.shard.constants.MaskConstants.DEFAULT_WHITE_LIST_NAMES;
import static com.ctrip.corp.obt.shard.constants.MaskConstants.MASK_PATTERN;

import java.util.Optional;

import com.ctrip.corp.obt.shard.configuration.DataShardProperties;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 匹配字段名为掩码白名单的类型名，且取值带*的掩码数据
 *
 * @author xukang zhang
 * @date 2023/11/13 16:58
 */
@AllArgsConstructor
@Slf4j
public class AllowedMaskForbiddenMatcher implements UpdateForbiddenMatcher {
    private final DataShardProperties dataShardProperties;

    @Override
    public boolean match(String propertyName, Object propertyValue, Object parameterObject, String columnName) {
        return false;
    }

    @Override
    public boolean skip(String propertyName, Object propertyValue, Object parameterObject, String columnName) {
        if (!(propertyValue instanceof String)) {
            return false;
        }
        return MASK_PATTERN.matcher((String) propertyValue).matches() && matchPropertyName(propertyName);
    }


    @Override
    public int order() {
        return -50;
    }


    private boolean matchPropertyName(String propertyName) {
        return DEFAULT_WHITE_LIST_NAMES.contains(propertyName)
            || Optional.ofNullable(dataShardProperties.getCommonAllowedMaskNames())
                .map(list -> list.contains(propertyName)).orElse(false);
    }
}
